package com.weilai.common.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weilai.common.model.DrawRecord;
import com.weilai.common.model.MedalRecord;
import com.weilai.common.model.Prize;
import com.weilai.common.model.SysUser;
import com.weilai.common.service.DrawRecordService;
import com.weilai.common.service.MedalRecordService;
import com.weilai.common.service.PrizeService;
import com.weilai.common.utils.StringRandom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * Created by Song on 2017/6/4.
 */
@Controller
@RequestMapping("/prize")
public class PrizeController {
    @Autowired
    PrizeService prizeService;
    @Autowired
    MedalRecordService medalRecordService;
    @Autowired
    DrawRecordService drawRecordService;

    /**
     * 跳转到添加奖品界面
     * @return
     */
    @RequestMapping("/toAddPrize")
    public String toAddPrize(){
        return "houtai/add_present";
    }


    /**
     * 添加奖品
     * @param model
     * @param prize
     * @return
     */
    @RequestMapping("/addPrize")
    public String addPrize(HttpServletRequest request,MultipartFile file, Model model, @ModelAttribute Prize prize){
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
//        String fileName = new Date().getTime()+".jpg";
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
        prize.setPrizeImgurl(request.getContextPath()+"/upload/"+fileName);
        //httpcode 界面用的状态码  200代表成功   400 代表失败  （假的）
        if (prizeService.addPrize(prize)== 1){
            model.addAttribute("httpCode","200");
            model.addAttribute("code", StringRandom.getStringRandom(8));
        }else{
            model.addAttribute("httpCode","400");
        }
        return "houtai/add_present";
    }


    /**
     * 修改奖品
     * @param model
     * @param prize
     * @return
     */
    @RequestMapping("/updatePrize")
    public String updatePrize(@RequestParam(value = "file", required = false) MultipartFile file,Model model, @ModelAttribute Prize prize,HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
//        String fileName = new Date().getTime()+".jpg";
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
        prize.setPrizeImgurl(request.getContextPath()+"/upload/"+fileName);
        //httpcode 界面用的状态码  200代表成功   400 代表失败  （假的）
        if (prizeService.updatePrize(prize)== 1){
            model.addAttribute("httpCode","200");
        }else{
            model.addAttribute("httpCode","400");
        }
        return "";
    }

    /**
     * 删除奖品
     * @param model
     * @param prize
     * @return
     */
    @RequestMapping("/delPrize")
    public String delPrize(Model model, @ModelAttribute Prize prize){
        //httpcode 界面用的状态码  200代表成功   400 代表失败  （假的）
        if (prizeService.delPrize(prize)== 1){
            model.addAttribute("httpCode","200");
            model.addAttribute("code", StringRandom.getStringRandom(8));
        }else{
            model.addAttribute("httpCode","400");
        }
        return "";
    }

    /**
     * 查询所有奖品
     * @param model
     * @return
     */
    @RequestMapping("/findPrizeList")
    public String findPrizeList(int pageNum,int pageSize,Model model){
        //赋值页面页码大小自动帮我们计算，我们只需要在页面上使用PageInfo的数据就行
        PageHelper.startPage(pageNum, pageSize);
        Page<Prize> prizeList = (Page) prizeService.findPrizeList(new Prize());
        //分页信息
        PageInfo<Prize> pageInfo = new PageInfo(prizeList);
        model.addAttribute("page",pageInfo);
        return "front/index";
    }

    /**
     * 前台查询所有奖品
     * @return
     */
    @RequestMapping(value ="frontfindPrizeList",method = {RequestMethod.POST})
    @ResponseBody
    public List<Prize> frontfindPrizeList(){
        List<Prize> prizeList = prizeService.findPrizeList(new Prize());
        return prizeList;
    }

    /**
     * 通过奖品名称搜索奖品
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/findByPrizeName")
    public String findByPrizeName(@RequestParam(required = false,defaultValue = "1") int pageNum,
                                  @RequestParam(required = false,defaultValue = "10")int pageSize,Model model,@RequestParam Prize prize){
        //赋值页面页码大小自动帮我们计算，我们只需要在页面上使用PageInfo的数据就行
        PageHelper.startPage(pageNum, pageSize);
        Page<Prize> prizeList = (Page) prizeService.findPrizeList(prize);
        //分页信息
        PageInfo<Prize> pageInfo = new PageInfo(prizeList);
        model.addAttribute("page",pageInfo);
        return "front/index";
    }


    /**
     * 前台通过奖品名称搜索奖品
     * @return
     */
    @RequestMapping(value="frontFindByPrizeName",method = {RequestMethod.POST})
    @ResponseBody
    public List<Prize> frontFindByPrizeName(@RequestBody Prize prize,HttpServletResponse response){
        List<Prize> prizeList = prizeService.findPrizeList(prize);
//        model.addAttribute("prizeList",prizeList);
        return prizeList;
    }

    /**
     * 前台通过奖品id搜索奖品
     * @return
     */
    @RequestMapping(value = "frontFindById",method = RequestMethod.POST)
    @ResponseBody
    public Prize findById(@RequestBody Prize  prize ){
//        model.addAttribute("prizeList",prizeList);
        return prizeService.findById(prize.getId());
    }

//    /**
//     * 前台点击我要兑换
//     * @param id
//     * @return
//     */
//    @RequestMapping(value = "frontDuiHuan",method = RequestMethod.POST)
//    @ResponseBody
//    public void findById(@RequestBody Integer id,HttpServletRequest request ){
//        //获得当前用户
//        SysUser user = (SysUser) request.getSession().getAttribute("user");
//        //插入到奖品记录表中
//        Prize prize = prizeService.findById(id);
//        DrawRecord drawRecord = new DrawRecord();
//        drawRecord.setDrawTime(new Date());
//        drawRecord.setUser(user);
//        drawRecord.setCashPrizeState("0");
//        drawRecord.setPrize(prize);
//        drawRecordService.add(drawRecord);
//    }




    /**
     * 前台点击兑换  修改奖品状态
     * @param prize
     * @param request
     * @return
     */
    @RequestMapping(value="frontDuihuan",method = {RequestMethod.POST})
    @ResponseBody
    public Integer duihuan(@RequestBody Prize prize, HttpServletRequest request){
        //得到奖奖品的id
        //查询改奖品需要兑换的奖章数量
        Prize prize0 = prizeService.findById(prize.getId());
        Integer medalCount = prize0.getMedalCount();
        //得到当前用户
        SysUser user = (SysUser) request.getSession().getAttribute("user");
//        SysUser user = new SysUser();
//        user.setId(2);
        //得到当前用户奖章数量
        MedalRecord medalRecord = new MedalRecord();
        medalRecord.setUser(user);
        MedalRecord byUser = medalRecordService.findByUserOfMedalRecordCount(medalRecord);
        Integer medalCount1 = byUser.getMedalCount();//46
        //判断奖章数量是否满足
        if(medalCount <= medalCount1){
            //满足
            //添加奖章记录
            medalRecord.setMedalCount(medalCount1-prize0.getMedalCount());
            medalRecord.setDuihuanTime(new Date());
            medalRecord.setUseType("0");
            medalRecord.setCount(medalCount);
            medalRecord.setUser(user);
            medalRecordService.addMedalCount(medalRecord);
            //跟新兑奖记录
            DrawRecord drawRecord = new DrawRecord();
            drawRecord.setUser(user);
            drawRecord.setCashPrizeState("0");
            drawRecord.setDrawTime(new Date());
            drawRecord.setPrize(prize);
            drawRecordService.add(drawRecord);
            return 1;
        }else{
            return 0;
        }

    }

}
